﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using  ESOL.Common.Entity;
using ESOL.Business.Hr;
using ESOL.Business.Mst;
using ESOL.WinUI.UICommon;
using ESOL.Common;

namespace ESOL.WinUI.Hr
{
    public partial class frmMaintainEmployeePositionApplication : BaseForm.frmBaseDialogyBusinessForm
    {
        #region variable
        private HrPersonPositionApplicationEntity mSelectedPersonPositionApp;
        private MstPersonEntity mSelectedPerson;
        #endregion

        #region construction
        public frmMaintainEmployeePositionApplication()
        {
            InitializeComponent();
        }
        public frmMaintainEmployeePositionApplication(HrPersonPositionApplicationEntity entity)
        {
            InitializeComponent();
            mSelectedPersonPositionApp = entity;
            mSelectedPerson = MstPersonBs.GetMstPersonByID(entity.PromotionPerson);
        }
     
        #endregion

        #region function
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "PST", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit2, "PST", false);
        }

        private void SetFields()
        {
            BindOriginalPositionGrid();
            BindChangedPositionGrid();
            if (mSelectedPersonPositionApp == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(mSelectedPersonPositionApp.PromotionPerson) == false)
            {
                mSelectedPerson = MstPersonBs.GetMstPersonByID(mSelectedPersonPositionApp.PromotionPerson);
                txtPromotionPerson.Text = mSelectedPerson.NameCn + " (" + mSelectedPerson.PersonCode + ")";
                txtPromotionPerson.Tag = mSelectedPerson;
            }
            if (string.IsNullOrEmpty(mSelectedPersonPositionApp.ApplicationPerson) == false)
            {
                MstPersonEntity appPerson = MstPersonBs.GetMstPersonByID(mSelectedPersonPositionApp.ApplicationPerson);
                txtApplicationPerson.Text = appPerson.NameCn + " (" + appPerson.PersonCode + ")";
                txtApplicationPerson.Tag = appPerson;
            }
            if (mSelectedPersonPositionApp.ApplicationDate.ToString("yyyy-MM-dd") == "1900-01-01" ||
                 mSelectedPersonPositionApp.ApplicationDate.ToString("yyyy-MM-dd") == "0001-01-01")
            {
                dtpApplicationDate.EditValue = "";
            }
            else
            {
                dtpApplicationDate.EditValue = mSelectedPersonPositionApp.ApplicationDate;
            }
            cmbStatus.SetSelectedValue(mSelectedPersonPositionApp.Status);
            txtReason.Text = mSelectedPersonPositionApp.Reason;
            txtApproveRemark.Text = mSelectedPersonPositionApp.ApprovedRemark;
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, mSelectedPersonPositionApp.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, mSelectedPersonPositionApp.ApprovedBy);

        }

        private void BindOriginalPositionGrid()
        {
            if (ThisActionType == ActionType.New)
            {
                if (mSelectedPerson == null)
                {
                    return;
                }
                DataSet ds = HrPersonPositionBs.GetPersonPositionById(mSelectedPerson.PersonId);
                if (ds != null && ds.Tables.Count > 0)
                {
                    gvOriginalPosition.DataSource = ds.Tables[0];
                }
                else
                {
                    gvOriginalPosition.DataSource = null;
                }
            }
            else
            {
                if (mSelectedPersonPositionApp == null)
                {
                    return;
                }
                gvOriginalPosition.DataSource = GetDataTable(mSelectedPersonPositionApp.OriginalPosition);
            }
        }

        private void BindChangedPositionGrid()
        {
            if (mSelectedPersonPositionApp == null)
            {
                gvChangedPosition.DataSource = HrPersonPositionBs.GetPersonPositionById("").Tables[0];

                return;
            }
            DataTable dt = GetDataTable(mSelectedPersonPositionApp.ChangedPosition);
            if(dt!=null)
            {
                gvChangedPosition.DataSource = dt;
            }
            else
            {
                DataTable dtNew = new DataTable();
                dtNew.Columns.Add("PERSON_ID");
                dtNew.Columns.Add("POSITION_ID");
                dtNew.Columns.Add("POSITION_NAME");
                dtNew.Columns.Add("POSITION_TYPE");
                dtNew.Columns.Add("SUPERVISOR");
                dtNew.Columns.Add("SUPERVISOR_NAME");
                DataRow dr = dtNew.NewRow();
                dr["PERSON_ID"] = mSelectedPerson.PersonId;
                dtNew.Rows.Add(dr);
                gvChangedPosition.DataSource = dtNew;
            }
        }

        private DataTable GetDataTable(string sValue)
        {
            if (string.IsNullOrEmpty(sValue))
                return null;
            DataTable dt = HrPersonPositionBs.GetPersonPositionById("").Tables[0];
            string[] positions = sValue.Split(new char[] { ';' });
            if (positions != null && positions.Length > 0)
            {
                for (int i = 0; i < positions.Length; i++)
                {
                    string[] personPosition = positions[i].Split(new char[] { '_' });
                    if (personPosition != null && personPosition.Length > 0)
                    {
                        DataRow dr = dt.NewRow();
                        string positionId = personPosition[0];
                        MstPositionEntity position = MstPositionBs.GetMstPositionByID(positionId);
                        string supervisor = personPosition[1];
                        string positionType = personPosition[2];
                        dr["PERSON_ID"] = mSelectedPerson.PersonId;
                        dr["POSITION_ID"] = positionId;
                        dr["POSITION_NAME"] = position.PositionName;
                        dr["POSITION_TYPE"] = positionType;
                        if (string.IsNullOrEmpty(supervisor) == false)
                        {
                            MstPersonEntity person = MstPersonBs.GetMstPersonByID(supervisor);
                            if (person != null)
                            {
                                dr["SUPERVISOR"] = supervisor;
                                dr["SUPERVISOR_NAME"] = person.NameCn;
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    bool isSuccessful = HrPersonPositionApplicationBs.InsertHrPersonPositionApplication(mSelectedPersonPositionApp);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    bool isSuccessful = HrPersonPositionApplicationBs.UpdateHrPersonPositionApplication(mSelectedPersonPositionApp);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    mSelectedPersonPositionApp.ApprovedDate = DateTime.Now;
                    mSelectedPersonPositionApp.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    mSelectedPersonPositionApp.ApprovedRemark = txtApproveRemark.Text;
                    bool isSuccessful = HrPersonPositionApplicationBs.ApprovePersonPositionApplication(mSelectedPersonPositionApp);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool CheckData()
        {
            if (mSelectedPerson == null)
            {
                MessageBox.Show("调职人员不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtReason.Text))
            {
                MessageBox.Show("调职理由不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtApplicationPerson.Text))
            {
                MessageBox.Show("申请人员不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpApplicationDate.EditValue == null)
            {
                MessageBox.Show("申请日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private void SetEntity()
        {
            if (mSelectedPersonPositionApp == null)
            {
                mSelectedPersonPositionApp = new HrPersonPositionApplicationEntity();
                mSelectedPersonPositionApp.ApplicationId = Guid.NewGuid().ToString();
            }
            if (mSelectedPerson != null)
            {
                mSelectedPersonPositionApp.PromotionPerson = mSelectedPerson.PersonId;
            }
            if (txtApplicationPerson.Tag != null && txtApplicationPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                mSelectedPersonPositionApp.ApplicationPerson = ((MstPersonEntity)txtApplicationPerson.Tag).PersonId;
            }
            if (dtpApplicationDate.EditValue!=null)
            {
                mSelectedPersonPositionApp.ApplicationDate = Convert.ToDateTime(dtpApplicationDate.EditValue);
            }
            else
            {
                mSelectedPersonPositionApp.ApplicationDate = Convert.ToDateTime("1900-01-01");
            }
            mSelectedPersonPositionApp.Status = "STATUS02";
            mSelectedPersonPositionApp.Reason = txtReason.Text;
            mSelectedPersonPositionApp.ApprovedRemark = txtApproveRemark.Text;

            if (ThisActionType == ActionType.New)
            {
               mSelectedPersonPositionApp.OriginalPosition = GetString((DataTable)gvOriginalPosition.DataSource);
            }
               mSelectedPersonPositionApp.ChangedPosition = GetString((DataTable)gvChangedPosition.DataSource);

        }

        private string GetString(DataTable dt)
        {
            string sValue = "";
            if (dt == null || dt.Rows.Count == 0)
            {
                return "";
            }
            foreach (DataRow dr in dt.Rows)
            {
                string positionId = "";
                string supervisor = "";
                string positionType = "";
                if (dr["POSITION_ID"] != null)
                {
                    positionId = dr["POSITION_ID"].ToString();
                }
                if (dr["POSITION_TYPE"] != null)
                {
                    positionType = dr["POSITION_TYPE"].ToString();
                }
                if (dr["SUPERVISOR"] != null)
                {
                    supervisor = dr["SUPERVISOR"].ToString();
                }
                if (string.IsNullOrEmpty(sValue))
                {
                    sValue = positionId + "_" + supervisor + "_" + positionType;
                }
                else
                {
                    sValue += ";" + positionId + "_" + supervisor + "_" + positionType;
                }
            }
            return sValue;
        }

        private void ResetControlsEnable()
        {
            txtApproveRemark.Enabled=false;

            if (ThisActionType == ActionType.Approve)
            {
              txtApproveRemark.Enabled = false;
            }
        }
        #endregion

        #region events
        protected override void OnShown(EventArgs e)
        {
            BindComboBox();
            SetFields();
            ResetControlsEnable();
            if (ThisActionType == ActionType.New)
            {
                txtApplicationPerson.Text = CommonParameter.CurrentUser.PersonEntity.NameCn + " (" + CommonParameter.CurrentUser.PersonEntity.PersonCode + ")";
                txtApplicationPerson.Tag = CommonParameter.CurrentUser.PersonEntity;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                return;
            }
        }
        protected override void Click_Approve()
        {
            if (mSelectedPersonPositionApp == null)
            {
                return;
            }
            mSelectedPersonPositionApp.Status = "STATUS03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (mSelectedPersonPositionApp == null)
            {
                return;
            }
            mSelectedPersonPositionApp.Status = "STATUS04";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        private void txtPromotionPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {

                mSelectedPerson = frm.SelectedPerson;
                SetFields();
                txtPromotionPerson.Text = frm.SelectedPerson.NameCn + " (" + frm.SelectedPerson.PersonCode + ")";
                txtPromotionPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                mSelectedPerson = null;
                SetFields();
            }
        }
        private void txtApplicationPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
                {
                    txtApplicationPerson.Text = frm.SelectedPerson.NameCn + " (" + frm.SelectedPerson.PersonCode + ")";
                    txtApplicationPerson.Tag = frm.SelectedPerson;
                }
                else
                {
                    txtApplicationPerson.Text = "";
                    txtApplicationPerson.Tag = null;
                }
            
        }

        private void itemAdd_Click(object sender, EventArgs e)
        {
            DataTable dt = gvChangedPosition.DataSource as DataTable;

            DataRow dr = dt.NewRow();
            dr["PERSON_ID"] = mSelectedPerson.PersonId;
            dt.Rows.Add(dr);

            
        }
        private DataRow mselectRow;

        private void itemDelete_Click(object sender, EventArgs e)
        {
            if (gridView2.DataSource == null)
            {
                return;
            }
            if (mselectRow == null)
            {
                return;
            }
            DataTable dt = gvChangedPosition.DataSource as DataTable;
            dt.Rows.Remove(mselectRow);
        }

        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            mselectRow = gridView2.GetDataRow(e.FocusedRowHandle);
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPositionQuery frm = new frmMaintainPositionQuery();
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                mselectRow["POSITION_ID"] = frm.SelectedPosition.PositionId;
                mselectRow["POSITION_NAME"] = frm.SelectedPosition.PositionName;

            }

        }

        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                mselectRow["SUPERVISOR"] = frm.SelectedPerson.PersonId;
                mselectRow["SUPERVISOR_NAME"] = frm.SelectedPerson.NameCn;
            }
        }

        #endregion
    }
}
